<script setup>
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import comps from "@/components/utils/component_selector.js"
import { computed, defineProps, ref } from 'vue'
const { vm } = defineProps(["vm"]);
const _mode = ref(vm.mode);

const controls = computed(() => {
  let childs = vm.META?.controls;
  return childs;
});

const resources = computed(() => {
  let childs = vm.META?.resources || [];
  return childs;
});

const hasParent = computed(() => {
  return vm.parentVm != null;
});

const vmMode = computed({
  get() {
    return _mode.value;
  },
  set(newValue) {
    _mode.value = newValue;
    vm.setMode(newValue);
  }
});

const layout = {
  innerHeight: window.innerHeight,
  innerWidth: window.innerWidth
}

const layoutRef = ref(layout);

function goBack() {
  if (vm.parentVm) {
    vm.parentVm.setView();
  }
}

function handleEdit() {
  if (vm.mode == 'browse') {
    vmMode.value = "edit";
  }
}

function handelCancel() {
  if (vm.mode == 'edit') {
    vmMode.value = "browse";
  } else if (vm.mode == 'add') {
    vmMode.value = "browse";
  }
}

function handleSave(args) {
  args.callback = (x => {
    let willGoBack = false;
    if (vm.mode == 'add') {
      willGoBack = true;
    }
    vmMode.value = "browse";
    if (willGoBack) {
      goBack();
    } else {
      vm.reLoad();
    }
  });

  vm.execute("save", args);
}

</script>
<template>
  <el-config-provider :locale="zhCn">
    <div class="common-layout">
      <el-container direction="vertical">
        <div>
          <div v-if="hasParent" style="display: block; float: left;">
            <el-button size="small" :text="true" @click="goBack">返 回</el-button>
          </div>
          <div style="display: block; float: right; margin-right: 1em;">
            <el-button @click="handleEdit">编 辑</el-button>
          </div>
        </div>
        <el-scrollbar height="700">
          <component v-for="child in controls" :is="comps(child)" :meta="child" :vm="vm" />
          <component v-for="child in resources" :is="comps(child)" :meta="child" :vm="vm" />
        </el-scrollbar>
      </el-container>
      <div v-if="vmMode != 'browse'" style="text-align: right; padding-right: 2em;">
        <el-button @click="handelCancel">取 消</el-button>
        <el-button type="primary" @click='handleSave({ "model": "~" })'>保 存</el-button>
      </div>
    </div>
  </el-config-provider>
</template>
<script>
window.addEventListener("resize", () => {
  // layout.innerHeight = window.innerHeight;
  // layout.innerWidth = window.innerWidth;
  // layoutRef.value = {}
});
</script>